package org.bigk.invoices.actions.info;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.bigk.invoices.actions.InvoicesActionSupport;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;


@Controller
@Namespace("/")
@Results({
	@Result(name = com.opensymphony.xwork2.Action.SUCCESS, location = "/pages/info/info.jsp")
})
public class InfoAction extends InvoicesActionSupport {
	
	private static final long serialVersionUID = 0x54e9c399503b9f5L;
	
	private static final Logger logger = LoggerFactory.getLogger(InfoAction.class);

	private UserDetails user;
	
	@Action("InfoAction")
	public String execute() {
		logger.debug("execute() - start");
		
		UserDetails user = currentUserDetails();
		setUser(user);
		logger.debug("execute() - retrieved and set UserDetails: [{}]", user);

		logger.debug("execute() - end - return value=[{}]", SUCCESS);
		return SUCCESS;
	}
	
	private UserDetails currentUserDetails() {
	    Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
	    if (principal == null) {
	        return null;
	    }
	    if (UserDetails.class.isAssignableFrom(principal.getClass())) {
	        return UserDetails.class.cast(principal);
	    }
	    return null;
	}

    public UserDetails getUser() {
        return user;
    }

    public void setUser(UserDetails user) {
        this.user = user;
    }
}
